
package com.yimixian.app.address;

import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.R;
import com.yimixian.app.adapter.PoiListViewAdapter;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.YmxTitleBarActivity;
import com.yimixian.app.util.ObservableUtils;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import rx.Subscription;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.util.ArrayList;

public class SearchPoiActivity extends YmxTitleBarActivity {

    public static final String EXTRA_MUTABLE_ADDRESS = "extra_mutable_address";

    @InjectView(R.id.poi_search_edit_text)
    EditText mPoiSearchEditText;
    @InjectView(R.id.poi_list_view)
    ListView mPoiListView;
    @InjectView(R.id.progress_bar)
    ProgressBar mProgressBar;
    @InjectView(R.id.list_progress_bar)
    View mListProgressBar;

    private PoiSearch mPoiSearch;
    private GeoCoder mBaiduGeoCoder;
    private Subscription mLocatingSubscription;
    private ArrayList<PoiInfo> mPoiInfoList;
    private PoiListViewAdapter mPoiListViewAdapter;
    private MutableAddress mAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAddress = getIntent().getParcelableExtra(EXTRA_MUTABLE_ADDRESS);
        if (mAddress == null || Strings.isNullOrEmpty(mAddress.city)) {
            finish();
            return;
        }

        setContentView(R.layout.search_poi_activity);
        ButterKnife.inject(this);

        mPoiSearch = PoiSearch.newInstance();
        mBaiduGeoCoder = GeoCoder.newInstance();

        mPoiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                mListProgressBar.setVisibility(View.INVISIBLE);
                if (poiResult == null || poiResult.getAllPoi() == null) {
                    mPoiInfoList = null;
                } else {
                    mPoiInfoList = new ArrayList<>();
                    for (PoiInfo poiInfo : poiResult.getAllPoi()) {
                        if (!poiInfo.address.contains(";")) {
                            mPoiInfoList.add(poiInfo);
                        }
                    }
                }
                mPoiListViewAdapter.setList(mPoiInfoList);
                mPoiListViewAdapter.notifyDataSetChanged();
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }
        });

        mPoiSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mLocatingSubscription = ObservableUtils.unsubscribe(mLocatingSubscription);
                mProgressBar.setVisibility(View.INVISIBLE);

                String str = s.toString();
                if (Strings.isNullOrEmpty(str)) {
                    mPoiInfoList = null;
                    mPoiListViewAdapter.setList(mPoiInfoList);
                    mPoiListViewAdapter.notifyDataSetChanged();
                    mListProgressBar.setVisibility(View.INVISIBLE);
                    return;
                }

                mPoiSearch.searchInCity(new PoiCitySearchOption()
                        .city(mAddress.city)
                        .keyword(str)
                        .pageCapacity(20));
                mListProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mPoiListViewAdapter = new PoiListViewAdapter(this);
        mPoiListViewAdapter.setList(mPoiInfoList);
        mPoiListView.setAdapter(mPoiListViewAdapter);
        mPoiListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mPoiSearchEditText.getWindowToken(), 0);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {

            }
        });

        mPoiListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MobclickAgent.onEvent(SearchPoiActivity.this,
                        StatConstants.SEARCH_POI_RESULT_ITEM_CLICK);
                mLocatingSubscription = ObservableUtils.unsubscribe(mLocatingSubscription);
                PoiInfo poiInfo = mPoiListViewAdapter.mList.get(position);
                mAddress.poiId = "bd-" + poiInfo.uid;
                mAddress.poiName = poiInfo.name;
                mAddress.poiAddress = poiInfo.address;
                if (poiInfo.location == null) {
                    UiUtils.showToast("poi信息为空");
                    return;
                }
                mAddress.latitude = String.valueOf(poiInfo.location.latitude);
                mAddress.longitude = String.valueOf(poiInfo.location.longitude);
                setResult(RESULT_OK, new Intent().putExtra(EXTRA_MUTABLE_ADDRESS, mAddress));
                finish();
            }
        });

        if (!Strings.isNullOrEmpty(mAddress.poiName)) {
            mPoiSearchEditText.setText(mAddress.poiName);
            mPoiSearchEditText.setSelection(mAddress.poiName.length());
        }
    }

    @Override
    protected void onDestroy() {
        if(mPoiSearch!=null) {
            mPoiSearch.destroy();
        }
        if(mBaiduGeoCoder != null) {
            mBaiduGeoCoder.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected String getTitleBarText() {
        return "选择地址";
    }

}
